package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.AttachCategoryEnumWaybill;
import cn.huiyunche.base.service.enums.AttachTypeEnum;
import cn.huiyunche.base.service.enums.DAccidentStatusEnum;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.TmsDAccidentService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.DAccidentMapper;
import cn.huiyunche.base.service.mappers.DWaybillAttachMapper;
import cn.huiyunche.base.service.mappers.ext.DAccidentViewMapper;
import cn.huiyunche.base.service.model.DAccident;
import cn.huiyunche.base.service.model.DWaybillAttach;
import cn.huiyunche.base.service.model.DWaybillAttachExample;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.*;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TmsDAccidentServiceImpl implements TmsDAccidentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TmsDAccidentServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private DAccidentMapper dAccidentMapper = null;

    @Autowired
    private DAccidentViewMapper dAccidentViewMapper = null;

    @Autowired
    private DWaybillAttachMapper dWaybillAttachMapper = null;

    private DAccidentViewMapper getDAccidentViewMapper() {
        return this.dAccidentViewMapper;
    }

    private DWaybillAttachMapper getDWaybillAttachMapper() {
        return this.dWaybillAttachMapper;
    }

    private DAccidentMapper getDAccidentMapper() {
        return this.dAccidentMapper;
    }

    private UserService getUserService() {
        return this.userService;
    }

    @Override
    public Result<Object> modify(Long id, Long waybillId, String description, String picKeys) throws Exception {
        LOGGER.info("add params id: {}, waybillId: {}, description: {}, picKeys: {}", id, waybillId, description,
                picKeys);
        Result<Object> result = new Result<>(true, null, "事故申报成功");
        if (waybillId == null || waybillId == 0) {
            LOGGER.info("waybillid is not null");
            throw new BusinessException("运单ID不能为空");
        } else if (StringUtils.isBlank(description)) {
            LOGGER.info("description is not null");
            throw new BusinessException("描述不能为空");
        } else if (StringUtils.isBlank(picKeys)) {
            LOGGER.info("picKeys is not null");
            throw new BusinessException("事故图片不能为空");
        }
        if (null != id && id != 0) {
            // 删除附件信息
            DWaybillAttachExample example = new DWaybillAttachExample();
            example.createCriteria().andWaybillIdEqualTo(waybillId)
                    .andCategoryEqualTo(AttachCategoryEnumWaybill.ACCIDENT.getValue());
            this.getDWaybillAttachMapper().deleteByExample(example);
            // 删除事故信息
            this.getDAccidentMapper().deleteByPrimaryKey(id);
        }
        UserShowVo currentUser = this.getUserService().getCurrentUser();
        LOGGER.info("current user: {}", currentUser);
        if (null == currentUser) {
            LOGGER.info("current user is not exist");
            throw new BusinessException("当前用户不存在");
        }
        // 构建事故对象
        DAccident dAccident = new DAccident();
        dAccident.setCreateTime(new Date());
        dAccident.setDescription(description);
        dAccident.setUserId(currentUser.getId());
        dAccident.setUserName(currentUser.getRealName());
        dAccident.setWaybillId(waybillId);
        dAccident.setStatus(DAccidentStatusEnum.AUDITING.getValue());
        result.setData(this.getDAccidentMapper().insertSelective(dAccident));
        List<String> picLists = JSONArray.parseArray(picKeys, String.class);
        if (CollectionUtils.isNotEmpty(picLists)) {
            picLists.stream().filter(value -> !"".equals(value)).forEach(value -> {
                // 保存事故附件
                DWaybillAttach attach = new DWaybillAttach();
                attach.setUserId(currentUser.getId());
                attach.setUserName(currentUser.getRealName());
                attach.setPicKey(value);
                attach.setWaybillId(waybillId);
                attach.setCategory(AttachCategoryEnumWaybill.ACCIDENT.getValue());
                attach.setType(AttachTypeEnum.ACCIDENT_PHOTO.getValue());
                this.getDWaybillAttachMapper().insertSelective(attach);
            });
        }
        return result;
    }

    @Override
    public Result<Map<String, Object>> list(PageVo pageVo) throws Exception {
        LOGGER.info("List params pageVo: {}", pageVo);
        Result<Map<String, Object>> result = new Result<>(true, null, "数据加载成功");
        Map<String, Object> map = new HashMap<>();
        UserShowVo userShowVo = this.getUserService().getCurrentUser();
        LOGGER.info("current user: {}", userShowVo);
        if (null == userShowVo) {
            LOGGER.info("current user is null");
            throw new BusinessException("当前用户不能为空");
        }
        try {
            pageVo.setTotalRecord(this.getDAccidentViewMapper().countByExample(userShowVo.getId()));
            List<DAccidentVo> vos = this.getDAccidentViewMapper().selectByExample(pageVo, userShowVo.getId());
            if (CollectionUtils.isNotEmpty(vos)) {
                vos.stream().forEach(v -> {
                    v.setShowDate(DateUtils.getStringFromDate(v.getCreateTime(), "yyyy-MM-dd"));
                });
            }
            LOGGER.info("selectByExample vos.size(): {}", vos.size());
            map.put("page", pageVo);
            map.put("accidents", vos);
            result.setData(map);
        } catch (Exception e) {
            LOGGER.error("select Daccident error: {}", e);
            throw new BusinessException("查询事故数据异常");
        }
        return result;
    }

    @Override
    public Result<DAccidentVo> selectDAccident(Long waybillId) throws Exception {
        LOGGER.info("selectDAccident params waybillId: {}", waybillId);
        Result<DAccidentVo> result = new Result<>(true, null, "数据加载成功");
        if (null == waybillId || waybillId == 0) {
            LOGGER.info("waybillId is not null");
            throw new BusinessException("运单ID不能为空");
        }
        List<DAccidentVo> vos = this.getDAccidentViewMapper().selectAccidentByWaybillId(waybillId);
        if (CollectionUtils.isNotEmpty(vos)) {
            List<AttachVo> attachVos = vos.get(0).getAttachVos();
            if (CollectionUtils.isNotEmpty(attachVos)) {
                attachVos.stream().filter(value -> !"".equals(value.getPicKey())).forEach(value -> {
                    value.setPicURL(QiniuUtils.generateDownloadTicket(value.getPicKey(), ""));
                });
            }
            result.setData(vos.get(0));
            return result;
        }
        return result;
    }

    @Override
    public Result<Map<String, Object>> listAdmin(PageVo pageVo, String orderCode) throws Exception {
        LOGGER.info("listAdmin params pageVo: {}, orderCode: {}", pageVo, orderCode);
        Result<Map<String, Object>> result = new Result<>(true, null, "数据加载成功");
        Map<String, Object> map = new HashMap<>();
        try {
            pageVo.setTotalRecord(this.getDAccidentViewMapper().daccidentCount(pageVo, orderCode));
            List<DAccidentVo> vos = this.getDAccidentViewMapper().selectDaccidentByExample(pageVo, orderCode);
            LOGGER.info("selectByExample vos.size(): {}", vos.size());
            map.put("page", pageVo);
            map.put("accidents", vos);
            result.setData(map);
        } catch (Exception e) {
            LOGGER.error("select Daccident error: {}", e);
            throw new BusinessException("查询事故数据异常");
        }
        return result;
    }

    @Override
    public Result<Object> auditAccident(Long id, int status) throws Exception {
        LOGGER.info("auditAccident params id: {}, status: {}", id, status);
        Result<Object> result = new Result<>(true, null, "审核成功");
        if (null == id || id == 0) {
            LOGGER.info("id is not null");
            throw new BusinessException("事故ID不能为空");
        } else if ("".equals(status)) {
            LOGGER.info("status is not null");
            throw new BusinessException("审核状态不能为空");
        }
        int en = DAccidentStatusEnum.getByValue(status).getValue();
        if ("".equals(en)) {
            LOGGER.info("status error");
            throw new BusinessException("审核状态错误");
        }
        DAccident accident = new DAccident();
        accident.setId(id);
        accident.setStatus(en);
        result.setData(this.getDAccidentMapper().updateByPrimaryKeySelective(accident));
        return result;
    }

}
